<template>
  <div class="bill-statement">
    <a-row
      :wrap="true"
      type="flex"
      justify="space-between"
      align="middle"
      class="tab-row"
    >
      <a-tabs v-model:activeKey="activeTab" @change="onTabChange">
        <a-tab-pane
          v-for="item of statementTabs"
          :key="item.key"
          :tab="item.title"
        ></a-tab-pane>
      </a-tabs>
      <a-radio-group
        v-if="haveToggle"
        v-model:value="activeType"
        button-style="solid"
        @change="changeTotalType"
      >
        <a-radio-button value="table">表格</a-radio-button>
        <a-radio-button value="chart">图表</a-radio-button>
      </a-radio-group>
    </a-row>

    <section class="statistics" v-if="isAdjustTable">
      <a-row class="quantity" type="flex">
        <a-col class="text-center">
          <div class="number-width">
            {{ basicsInfo?.adjustContractNum || 0 }}
          </div>
          <div class="text">调整总合同数</div>
        </a-col>
        <a-col class="text-center">
          <div class="number-width">
            ￥{{ basicsInfo?.adjustPriceTotal || 0 }}
          </div>
          <div class="text">调整总金额</div>
        </a-col>
        <a-col class="text-center">
          <div class="number-width">{{ basicsInfo?.adjustBillNum || 0 }}</div>
          <div class="text">调整总账单数</div>
        </a-col>
        <a-col class="text-center">
          <div class="number-width">
            {{ basicsInfo?.ratioAdjust?.nums || 0 }}/{{
              (basicsInfo?.ratioAdjust?.ratio || 0) + "%"
            }}
          </div>
          <div class="text">比例调整数/占比</div>
        </a-col>
        <a-col class="text-center">
          <div class="number-width">
            {{ basicsInfo?.amountAdjust?.nums || 0 }}/{{
              (basicsInfo?.amountAdjust?.ratio || 0) + "%"
            }}
          </div>
          <div class="text">金额调整数/占比</div>
        </a-col>
      </a-row>
    </section>

    <a-form layout="vertical">
      <!--   应收应支报表查询   -->
      <a-row v-if="isIncomeAndExpenseTable || isIncomeAndExpenseChart" :wrap="true" class="search-row" :gutter="18" align="middle">
        <!--   应收应支报表查询 start   -->
        <a-col
          :xl="4"
          :lg="6"
          :md="8"
          :sm="12"
          :xs="16"
        >
          <a-form-item label="统计方式" :colon="false">
            <a-select
              placeholder="请选择统计方式"
              v-model:value="searchParams.income.method"
              :options="statisticsOption"
            />
          </a-form-item>
        </a-col>
        <a-col
          :xl="4"
          :lg="6"
          :md="8"
          :sm="12"
          :xs="16"
        >
          <a-form-item label="统计月份" :colon="false">
            <a-month-picker
              class="w-100p"
              v-model:value="searchParams.income.month"
              placeholder="请选择统计月份"
              :format="monthFormat"
              :valueFormat="monthFormat"
              :allowClear="false"
            />
          </a-form-item>
        </a-col>
        <a-col
          :xl="4"
          :lg="6"
          :md="8"
          :sm="12"
          :xs="16"
          v-if="isIncomeAndExpenseTable"
        >
          <a-form-item :label="BLCOMMON.utils.L('租客')" :colon="false">
            <a-input
              :placeholder="`请输入${BLCOMMON.utils.L('租客')}名称`"
              v-model:value="searchParams.income.owner_name"
            />
          </a-form-item>
        </a-col>
        <a-col
          :xl="4"
          :lg="6"
          :md="8"
          :sm="12"
          :xs="16"
          v-if="isIncomeAndExpenseTable"
        >
          <a-form-item label="联系电话" :colon="false">
            <a-input
              placeholder="请输入联系电话"
              v-model:value="searchParams.income.tel"
            />
          </a-form-item>
        </a-col>
        <a-col
          :xl="4"
          :lg="6"
          :md="8"
          :sm="12"
          :xs="16"
          v-if="isIncomeAndExpenseTable"
        >
          <a-form-item label="费用类型" :colon="false">
            <a-cascader
              v-model:value="searchParams.income.cost_type"
              :options="costTypeOption"
              :load-data="getCostTypeSub"
              placeholder="请选择"
              dropdownClassName="fee-type-cascader-custom"
            />
          </a-form-item>
        </a-col>
        <a-col
          :xl="4"
          :lg="6"
          :md="8"
          :sm="12"
          :xs="16"
          v-if="isIncomeAndExpenseTable"
        >
          <a-form-item label="逾期状态" :colon="false">
            <a-select
              v-model:value="searchParams.income.timeout_status"
              placeholder="请选择"
              :options="timeoutOption"
              allowClear
            ></a-select>
          </a-form-item>
        </a-col>
        <a-col
          :xl="4"
          :lg="6"
          :md="8"
          :sm="12"
          :xs="16"
          v-if="isIncomeAndExpenseTable"
        >
          <a-form-item label="滞纳金" :colon="false">
            <a-select
              v-model:value="searchParams.income.latefee_status"
              placeholder="请选择"
              :options="lateFeeOption"
              allowClear
            ></a-select>
          </a-form-item>
        </a-col>
        <a-col
          :xl="4"
          :lg="6"
          :md="8"
          :sm="12"
          :xs="16"
          v-if="isIncomeAndExpenseTable"
        >
          <a-form-item label="楼宇名称" :colon="false">
            <a-select
              v-model:value="searchParams.income.build_id"
              placeholder="请选择"
              :options="buildOption"
              allowClear
            ></a-select>
          </a-form-item>
        </a-col>
        <a-col
          :xl="4"
          :lg="6"
          :md="8"
          :sm="12"
          :xs="16"
          v-if="isIncomeAndExpenseTable"
        >
          <a-form-item label="房号" :colon="false">
            <a-input
              placeholder="请输入房号"
              v-model:value="searchParams.income.room_name"
            />
          </a-form-item>
        </a-col>
        <a-col
          :xl="4"
          :lg="6"
          :md="8"
          :sm="12"
          :xs="16"
          v-if="isIncomeAndExpenseTable"
        >
          <a-form-item label="收款方式" :colon="false">
            <a-select
              v-model:value="searchParams.income.remit_type"
              placeholder="请选择"
              :options="remitTypeOption"
              allowClear
            ></a-select>
          </a-form-item>
        </a-col>
        <a-col
          :xl="4"
          :lg="6"
          :md="8"
          :sm="12"
          :xs="16"
          v-if="isIncomeAndExpenseTable"
        >
          <a-form-item label="结清状态" :colon="false">
            <a-select
              v-model:value="searchParams.income.settle_status"
              placeholder="请选择"
              :options="settleOption"
              allowClear
            ></a-select>
          </a-form-item>
        </a-col>

        <a-col
          :xl="4"
          :lg="6"
          :md="8"
          :sm="12"
          :xs="16"
          v-if="isIncomeAndExpenseTable"
        >
          <a-form-item label="所属公司" :colon="false">
            <a-select
              v-model:value="searchParams.income.org_branch_id"
              placeholder="请选择"
              :options="companyList"
              mode="multiple"
              optionFilterProp="label"
              allowClear
            ></a-select>
          </a-form-item>
        </a-col>
        <a-col>
          <a-form-item label=" ">
            <a-space>
              <a-button type="primary" @click="handleSearch"> 查询 </a-button>
              <a-button @click="reset">重置</a-button>
            </a-space>
          </a-form-item>
        </a-col>
      </a-row>
      <!--  调整账单查询  -->
      <a-row :wrap="true" class="search-row" :gutter="18" align="middle" v-if="isAdjustTable">
        <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="16">
          <a-form-item :label="BLCOMMON.utils.L('租客')" :colon="false">
            <a-input
              :placeholder="`请输入${BLCOMMON.utils.L('租客')}名称`"
              v-model:value="searchParams.adjust.owner_name"
            />
          </a-form-item>
        </a-col>

        <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="16">
          <a-form-item label="项目名称" :colon="false">
            <a-select
              v-model:value="searchParams.adjust.village_ids"
              :options="villageList"
              placeholder="请选择项目"
              :allowClear="true"
              mode="multiple"
              optionFilterProp="label"
              style="width: 100%"
              @change="(value, option) => {onVillageChange(value, option, 'adjust')}"
            >
            </a-select>
          </a-form-item>
        </a-col>

        <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="16">
          <a-form-item label="楼宇名称" :colon="false">
            <a-select
              v-model:value="searchParams.adjust.build_ids"
              :options="buildList.adjust"
              placeholder="请选择楼宇"
              :allowClear="true"
              mode="multiple"
              optionFilterProp="label"
              style="width: 100%"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="16">
          <a-form-item label="合同编号" :colon="false">
            <a-input
              placeholder="搜索合同编号"
              v-model:value="searchParams.adjust.contract_number"
            />
          </a-form-item>
        </a-col>
        <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="16">
          <a-form-item label="账单编号" :colon="false">
            <a-input
              placeholder="搜索账单编号"
              v-model:value="searchParams.adjust.bill_number"
            />
          </a-form-item>
        </a-col>
        <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="16">
          <a-form-item label="调整类型" :colon="false">
            <a-select
              v-model:value="searchParams.adjust.adjust_type"
              :options="adjustTypeOption"
              placeholder="请选择调整类型"
              :allowClear="true"
              mode="multiple"
              optionFilterProp="label"
              style="width: 100%"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="16">
          <a-form-item label="所属公司" :colon="false">
            <a-select
              v-model:value="searchParams.adjust.org_branch_id"
              :options="companyList"
              placeholder="请选择"
              :allowClear="true"
              mode="multiple"
              optionFilterProp="label"
              style="width: 100%"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col>
          <a-form-item label=" ">
            <a-space>
              <a-button type="primary" @click="handleSearch"> 查询 </a-button>
              <a-button @click="reset">重置</a-button>
            </a-space>
          </a-form-item>
        </a-col>
      </a-row>
      <!--  结转账单查询  -->
      <a-row :wrap="true" class="search-row" :gutter="18" align="middle" v-if="isCarryOverTable">
        <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="16">
          <a-form-item label="业务类型" :colon="false">
            <a-select
              v-model:value="searchParams.carry.businessType"
              :options="carryOverType"
              placeholder="请选择业务类型"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
        <a-col
          :xl="4"
          :lg="6"
          :md="8"
          :sm="12"
          :xs="16"
        >
          <a-form-item label="费用类型" :colon="false">
            <a-cascader
              v-model:value="searchParams.carry.cost_type"
              :options="costTypeOption"
              :load-data="getCostTypeSub"
              placeholder="请选择"
              dropdownClassName="fee-type-cascader-custom"
            />
          </a-form-item>
        </a-col>
        <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="16">
          <a-form-item label="项目名称" :colon="false">
            <a-select
              v-model:value="searchParams.carry.village_ids"
              :options="villageList"
              placeholder="请选择项目"
              :allowClear="true"
              mode="multiple"
              optionFilterProp="label"
              style="width: 100%"
              @change="(value, option) => {onVillageChange(value, option, 'carry')}"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="16">
          <a-form-item label="楼宇名称" :colon="false">
            <a-select
              v-model:value="searchParams.carry.build_ids"
              :options="buildList.carry"
              placeholder="请选择楼宇"
              :allowClear="true"
              mode="multiple"
              optionFilterProp="label"
              style="width: 100%"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="16">
          <a-form-item label="转出对方名称" :colon="false">
            <a-input
              placeholder="请输入转出对方名称"
              v-model:value="searchParams.carry.out_owner_name"
            />
          </a-form-item>
        </a-col>
        <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="16">
          <a-form-item label="转入对方名称" :colon="false">
            <a-input
              placeholder="请输入转入对方名称"
              v-model:value="searchParams.carry.into_owner_name"
            />
          </a-form-item>
        </a-col>
        <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="16">
          <a-form-item label="转出账单编号" :colon="false">
            <a-input
              placeholder="请输入转出账单编号"
              v-model:value="searchParams.carry.out_bill_number"
            />
          </a-form-item>
        </a-col>
        <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="16">
          <a-form-item label="转入账单编号" :colon="false">
            <a-input
              placeholder="请输入转入账单编号"
              v-model:value="searchParams.carry.into_bill_number"
            />
          </a-form-item>
        </a-col>
        <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="16">
          <a-form-item label="结转创建时间">
            <a-range-picker
              v-model:value="searchParams.carry.createDate"
              :placeholder="['创建起始时间', '创建结束时间']"
              valueFormat="YYYY-MM-DD"
              format="YYYY-MM-DD"
              class="form-width"
            />
          </a-form-item>
        </a-col>
        <a-col>
          <a-form-item label=" ">
            <a-space>
              <a-button type="primary" @click="handleSearch"> 查询 </a-button>
              <a-button @click="reset">重置</a-button>
            </a-space>
          </a-form-item>
        </a-col>
      </a-row>

      <!--  收入单据查询    -->
      <a-row :wrap="true" class="search-row" :gutter="18" align="middle" v-if="isReceiptsTable">
        <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="16">
          <a-form-item :label="BLCOMMON.utils.L('租客')" :colon="false">
            <a-input
              :placeholder="`请输入${BLCOMMON.utils.L('租客')}名称`"
              v-model:value="searchParams.receipts.owner_name"
            />
          </a-form-item>
        </a-col>
        <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="16">
          <a-form-item label="项目名称" :colon="false">
            <a-select
              v-model:value="searchParams.receipts.village_ids"
              :options="villageList"
              placeholder="请选择项目"
              :allowClear="true"
              mode="multiple"
              optionFilterProp="label"
              style="width: 100%"
              @change="(value, option) => {onVillageChange(value, option, 'receipts')}"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="16">
          <a-form-item label="楼宇名称" :colon="false">
            <a-select
              v-model:value="searchParams.receipts.build_ids"
              :options="buildList.receipts"
              placeholder="请选择楼宇"
              :allowClear="true"
              mode="multiple"
              optionFilterProp="label"
              style="width: 100%"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="16">
          <a-form-item label="合同编号" :colon="false">
            <a-input
              placeholder="请输入合同编号"
              v-model:value="searchParams.receipts.contract_number"
            />
          </a-form-item>
        </a-col>
        <a-col :xl="4" :lg="6" :md="8" :sm="12" :xs="16">
          <a-form-item label="所属公司" :colon="false">
            <a-select
              v-model:value="searchParams.receipts.org_branch_id"
              :options="companyList"
              placeholder="请选择"
              :allowClear="true"
              mode="multiple"
              optionFilterProp="label"
              style="width: 100%"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col
          :xl="4"
          :lg="6"
          :md="8"
          :sm="12"
          :xs="16"
        >
          <a-form-item label="费用类型" :colon="false">
            <a-cascader
              v-model:value="searchParams.receipts.cost_type"
              :options="costTypeOption"
              :load-data="getCostTypeSub"
              placeholder="请选择"
              dropdownClassName="fee-type-cascader-custom"
            />
          </a-form-item>
        </a-col>
        <a-col
          :xl="4"
          :lg="6"
          :md="8"
          :sm="12"
          :xs="16"
        >
          <a-form-item label="收入月份" :colon="false">
            <a-month-picker
              class="w-100p"
              v-model:value="searchParams.receipts.income_month"
              placeholder="请选择收入月份"
              :format="monthFormat"
              :valueFormat="monthFormat"
              :allowClear="false"
            />
          </a-form-item>
        </a-col>
        <a-col>
          <a-form-item label=" ">
            <a-space>
              <a-button type="primary" @click="handleSearch"> 查询 </a-button>
              <a-button @click="reset">重置</a-button>
            </a-space>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <!-- 非调整金表格 -->
    <div class="statement-content" v-if="!isIncomeAndExpenseChart">
      <a-table
        sticky
        :dataSource="dataList"
        :columns="activeColumn"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        rowKey="id"
        :scroll="{ x: 'max-content' }"
        :row-selection="rowSelection"
        v-show="!isAdjustTable"
        :customRow="isCarryOverTable ? customRow : null"
      >
        <template #title>
          <a-row
            type="flex"
            justify="end"
            align="middle"
            v-if="isIncomeAndExpenseTable || isCarryOverTable || isReceiptsTable"
          >
            <a-button @click="downLoadClick(isCarryOverTable ? 'carry' : isReceiptsTable ? 'receipts' : 'income')"
              ><template #icon><DownloadOutlined /></template>
              导出报表</a-button
            >
          </a-row>
        </template>

        <template #bodyCell="{ text, record, index, column }">
          <template v-if="column.slotKey === 'owner_name'">
            <span
              :class="record.owner_id ? 'link' : ''"
              @click.stop="onOwnerClick(record.owner_id)"
              >{{ text || "--" }}</span
            >
          </template>
          <template v-if="column.slotKey === 'proprietor_name'">
            <span
              :class="record.owner_id || record.proprietor_id ? 'link' : ''"
              @click.stop="onOwnerCollectClick(record)"
              >{{
                record.owner_id
                  ? record.owner_name
                  : record.proprietor_id
                  ? record.proprietor_name || record.owner_name
                  : "--"
              }}</span
            >
          </template>
          <template v-if="column.slotKey === 'room_number'">
            <div v-if="record.build_bind && record.build_bind.room.length > 0">
              <RoomBuildBindInRecord :build_bind="record.build_bind"/>
            </div>
            <span v-else>--</span>
          </template>

          <template v-if="column.slotKey === 'notice_status'">
            <!-- 0:未发送； 2：已发送 -->
            <a-tag color="#ff3141" v-if="text == 0">{{
              record.notice_status_txt
            }}</a-tag>
            <a-tag color="#00b578" v-else>{{ record.notice_status_txt }}</a-tag>
          </template>

          <template v-if="column.slotKey === 'contract_number'">
            <span
              :class="record.contract_id ? 'link' : ''"
              @click.stop="onContractClick(record.contract_id)"
              >{{ text || "--" }}</span
            >
          </template>

          <template v-if="column.slotKey === 'action'">
            <a-button
              type="primary"
              size="small"
              v-if="isIncomeAndExpenseTable"
              @click.stop="addPaymentNoticeBatch('one', record.id)"
              style="margin-left: 10px"
              >生成缴费通知单</a-button
            >
          </template>

          <template v-if="column.slotKey === 'carry_out_bill_number'">
             <span
               :class="record.out_bill_id ? 'link' : ''"
               @click.stop="clickBillNum(record.out_bill_id)"
             >{{ text || "--" }}</span
             >
          </template>
          <template v-if="column.slotKey === 'carry_into_bill_number'">
            <span
              :class="record.into_build_id ? 'link' : ''"
              @click.stop="clickBillNum(record.into_build_id)"
            >{{ text || "--" }}</span
            >
          </template>
          <template v-if="column.slotKey === 'carry_out_owner_id'">
            <span
              :class="record.out_owner_id ? 'link' : ''"
              @click.stop="onOwnerClick(record.out_owner_id)"
            >{{ text || "--" }}</span
            >
          </template>
          <template v-if="column.slotKey === 'carry_into_owner_id'">
            <span
              :class="record.into_owner_id ? 'link' : ''"
              @click.stop="onOwnerClick(record.into_owner_id)"
            >{{ text || "--" }}</span
            >
          </template>
        </template>
      </a-table>
    </div>

    <!-- 调整金表格(调整金表格有子表格 所以需与其他表格隔离) -->
    <div class="statement-content" v-if="!isIncomeAndExpenseChart">
      <a-table
        sticky
        :dataSource="dataList"
        :columns="activeColumn"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        rowKey="id"
        :scroll="{ x: 'max-content' }"
        :row-selection="rowSelection"
        v-show="isAdjustTable"
        class="components-table-demo-nested"
      >
        <template #title>
          <a-row
            type="flex"
            justify="end"
            align="middle"
          >
            <a-button @click="downLoadClick('adjust')"
            ><template #icon><DownloadOutlined /></template>
              导出报表</a-button
            >
          </a-row>
        </template>
        <!--   子表格    -->
        <template #expandedRowRender="{ record, index, indent, expanded }">
          <a-table
            :columns="adjustInnerColumns"
            :data-source="record.adjust_data || []"
            :pagination="false"
          >
            <template #bodyCell="{ text, record, index, column }">
              <template v-if="column.slotKey === 'adjust_status'">
                <span
                  v-if="
                    record.approval_status == 1 || record.approval_status == 3
                  "
                  :style="{
                    color: record.approval_status == 1 ? '#fd1e1e' : '#faad14',
                  }"
                >
                  {{ record.approval_status_txt }}
                </span>
                <span
                  v-else
                  :style="{ color: record.adjust_status == 2 ? '#87d068' : '' }"
                >
                  {{ text }}
                </span>
              </template>
              <template v-if="column.slotKey === 'action'">
                <a-button
                  type="link"
                  :disabled="record.adjust_status !== 2"
                  v-if="canCancelAdjust"
                  @click.stop="handleAdjustRemove(record)"
                >
                  作废
                </a-button>
                <span v-else>--</span>
              </template>
            </template>
          </a-table>
        </template>

        <template #bodyCell="{ text, record, index, column }">
          <template v-if="column.slotKey === 'owner_name'">
            <span
              :class="record.owner_id ? 'link' : ''"
              @click="onOwnerClick(record.owner_id)"
              >{{ text || "--" }}</span
            >
          </template>

          <template v-if="column.slotKey === 'contract_number'">
            <span
              :class="record.contract_id ? 'link' : ''"
              @click="onContractClick(record.contract_id)"
              >{{ text || "--" }}</span
            >
          </template>

          <template v-if="column.slotKey === 'bill_number'">
            <a @click.stop="clickBillNum(record.id)">
              {{ text }}
            </a>
          </template>
        </template>
      </a-table>
    </div>

    <!-- 应收应支图表内容start -->
    <a-card v-if="isIncomeAndExpenseChart" :style="{ marginTop: '10px' }">
      <template #title>
        <div class="title-card-text">
          {{ activeTab === "1" ? "应收汇总" : "应支汇总" }}
        </div>
      </template>
      <a-spin :spinning="totalSpin">
        <div class="total-box">
          <div
            class="total-item"
            v-for="(item, index) in totalList"
            :key="index"
            :class="
              index <= 2
                ? index === 2
                  ? 'dec-left border-right'
                  : 'dec-left'
                : 'dec-right'
            "
          >
            <div class="item-dec">
              <a-tooltip
                placement="top"
                :title="item.num || 0"
                :visible="item.isOpen"
              >
                <div
                  class="total-num"
                  @mouseenter="
                    (e) => {
                      handleEnter(e, item);
                    }
                  "
                  @mouseleave="item.isOpen = false"
                >
                  ￥{{ item.num || 0 }}
                </div>
              </a-tooltip>
              <div class="total-dec">{{ item.title }}</div>
            </div>
          </div>
        </div>
      </a-spin>
    </a-card>

    <a-row
      v-show="isIncomeAndExpenseChart"
      :gutter="10"
      :wrap="true"
      :style="{ marginTop: '10px' }"
    >
      <a-col :span="8" style="height: 500px">
        <a-card
          style="height: 100%; display: flex; flex-direction: column"
          :bodyStyle="{ flex: 1, height: 0, padding: '10px 24px 24px 24px' }"
        >
          <template #title>
            <div class="title-card-text">
              {{ `${activeTab === "1" ? "已收" : "已支"}金额线下/线上占比` }}
            </div>
          </template>
          <a-spin :spinning="pieSpin">
            <div class="overview-box">
              <div
                v-show="pieData.length"
                id="bill-statement-report-pie"
                class="chart"
              ></div>
              <Empty
                style="margin-top: 200px"
                :image="simpleImage"
                v-if="pieData.length == 0"
              />
              <!--  antV G2 4.+ useHtml 属性移除， 暂时不支持使用 html 渲染图例，可以在外部自定义图例  -->
              <!--   自定义图例   -->
              <div class="custom-legend" v-if="pieData.length">
                <div
                  v-for="(item, index) in pieData"
                  :key="index"
                  class="custom-legend-item"
                >
                  <div class="item-count">{{ item.total }}</div>
                  <div class="item-title">
                    <div
                      class="circle"
                      :style="{ background: color[index] }"
                    ></div>
                    <div>{{ item.name }}</div>
                  </div>
                </div>
              </div>
            </div>
          </a-spin>
        </a-card>
      </a-col>
      <a-col :span="16" style="height: 500px">
        <a-card
          style="height: 100%; display: flex; flex-direction: column"
          :bodyStyle="{ flex: 1, height: 0, padding: '24px' }"
        >
          <template #title>
            <div class="title-card-text">费用类型趋势</div>
          </template>
          <template #extra> 单位：元 </template>
          <a-spin :spinning="barSpin">
            <div class="overview-box">
              <div
                v-show="barData.length"
                id="bill-statement-report-bar"
                class="chart"
              ></div>
              <Empty
                style="margin-top: 200px"
                :image="simpleImage"
                v-if="barData.length == 0"
              />
            </div>
          </a-spin>
        </a-card>
      </a-col>
    </a-row>
    <!-- 应收应支图表内容end -->

    <!-- 租客详情 -->
    <OwnerDetailDrawer
      :visible="ownerDetailVisible"
      :id="ownerId"
      @cancel="ownerDetailVisible = false"
    />

    <!-- 业主详情 -->
    <CreateProprietor
      :visible="proprietorDetailVisible"
      :id="proprietorId"
      drawerType="view"
      @onClose="proprietorDetailVisible = false"
    />

    <!--  生成缴费通知单  -->
    <add-notice
      @closeDrawer="addNoticeVisible = false"
      @success="addNoticeVisible = false"
      :visible="addNoticeVisible"
      :ids="addNoticeIds"
    >
    </add-notice>

    <!--  合同详情  -->
    <ContractDetailDrawer
      :visible="contractDetailVisible"
      :id="contractDetailId"
      @handleCancel="
        () => {
          contractDetailVisible = false;
        }
      "
    />

    <!-- 作废调整 -->
    <remove-adjust
      :visible="removeAdjustVisible"
      :id="removeAdjustId"
      :billId="removeAdjustBillId"
      @cancel="removeAdjustVisible = false"
      @success="handleAdjustRemoveSuccess"
    ></remove-adjust>

    <!-- 账单详情 -->
    <BillDetailDrawer
      :visible="billDetailVisible"
      :id="billDetailId"
      @cancel="cancelBill"
    />

    <!--  结转详情  -->
    <CarryOverDetail
      :visible="carryDetailVisible"
      :id="carryDetailId"
      @handleCancel="handleCancelCarryDetail"
      @handleRefresh="handleRefresh"
    />

    <!-- 导出表格 -->
    <ExportComponents
      v-if="isExport"
      :visible="isExport"
      :title="titles"
      url="/incomeConfirm/incomeReceiptList"
      service="/org"
      method="post"
      :params="paramses"
      :limit="10000"
      :columnstitle="listHanders"
      :custom_result="exportResult"
      :custom_data="true"
      @customDataFunc="handleCustomResult"
      @request="$utils.commonRequest"
      @cancel="handleChangeExport"
    />
  </div>
</template>

<script>
import {
  defineComponent,
  reactive,
  toRefs,
  computed,
  ref,
  onActivated,
  watch,
  defineAsyncComponent,
  onMounted,
  onUnmounted,
  nextTick,
  createVNode,
} from "vue";
import {
  DeleteOutlined,
  DownloadOutlined,
  ExclamationCircleOutlined,
  InsertRowAboveOutlined,
  SearchOutlined,
} from "@ant-design/icons-vue";
import request from "../../../common/utils/request";
import { useRouter, useRoute } from "vue-router";
import { Form, message, notification, Empty, Modal } from "ant-design-vue";
import utils from "../../../common/utils/utils";
import { xlsx } from "../../../common/utils/xlsx";

const useForm = Form.useForm;
import moment from "moment";
import store from "@/store";
import OwnerDetailDrawer from "@/views/village/OwnerManage/modules/OwnerDetailDrawer.vue";
import CreateProprietor from "@/views/contract/CostContract/modules/CreateProprietor.vue";
import AddNotice from "@/views/bill/AllBills/AddNotice.vue";
import { Chart } from "@antv/g2";
import _ from "lodash";
const monthFormat = "YYYY-MM";
import BLCOMMON from "bl-common-vue3";
import RemoveAdjust from "@/views/bill/BillDetail/modules/RemoveAdjust.vue";
import CarryOverDetail from "@/views/bill/BillDetail/modules/CarryOverDetail.vue";
const BillDetailDrawer = defineAsyncComponent(() =>
  import("@/views/bill/BillDetail/modules/BillDetailDrawer.vue")
);
const dateFormatStr = "YYYY-MM-DD";
const ContractDetailDrawer = defineAsyncComponent(() =>
  import("@/views/contract/ContractDetail/ContractDetailDrawer.vue")
);
import {ExportComponents} from "bl-common-vue3";
import RoomBuildBindInRecord from "@/components/RoomBuildBindInRecord/index.vue";

export default defineComponent({
  name: "billStatement",
  components: {
    RoomBuildBindInRecord,
    CarryOverDetail,
    BillDetailDrawer,
    RemoveAdjust,
    DeleteOutlined,
    AddNotice,
    OwnerDetailDrawer,
    InsertRowAboveOutlined,
    DownloadOutlined,
    SearchOutlined,
    CreateProprietor,
    Empty,
    ContractDetailDrawer,
    ExportComponents,
  },
  setup() {
    const $router = useRouter();
    const $route = useRoute();
    const simpleImage = ref(Empty.PRESENTED_IMAGE_SIMPLE);
    const canCancelAdjust = BLCOMMON.utils.getBtnPermission([
      "billList",
      "auth",
      "cancelAdjust",
    ]);

    const state = reactive({
      activeTab: "1", //  默认应收 1   应支 2
      activeType: "table",
      dataList: [],
      loading: false,
      page: 1,
      limit: 10,
      total: 0,
      costTypeOption: [], // 费用类型下拉
      timeoutOption: [], // 逾期状态下拉
      lateFeeOption: [], // 滞纳金状态下拉
      remitTypeOption: [], // 收款方式下拉
      settleOption: [], // 结清状态下拉
      buildOption: [], // 收支楼宇下拉
      billSourceOption: [], // 账单来源下拉
      currencyOption: [], // 币种下拉
      carryOverType: [
        {
          label: '全部',
          value: 0,
        },
        {
          label: '新建',
          value: 1,
        },
        {
          label: '作废',
          value: 2,
        },
      ],
      ownerId: 0,
      ownerDetailVisible: false,
      proprietorId: 0,
      proprietorDetailVisible: false,
      addNoticeVisible: false,
      addNoticeIds: [],
      totalAmount: 0,
      propertyAmount: 0,
      otherAmount: 0,
      needAmount: 0,
      haveAmount: 0,
      totalSpin: false,
      pieSpin: false,
      pieChart: {},
      color: ["#3aa1ff", "#79e0b8"],
      pieData: [],
      barChart: {},
      barSpin: false,
      barData: [],
      incomeColumns: INCOME_COLUMNS,
      expenseColumns: EXPENSE_COLUMNS,
      adjustColumns: ADJUST_COLUMNS,
      adjustInnerColumns: ADJUST_INNER_COLUMNS,
      carryOverColumns: CARRY_OVER_COLUMNS,
      receiptsColumns: RECEIPTS_COLUMNS,
      buildList: {
        adjust: [],
        carry: [],
        receipts: [],
      }, // 调整账单楼宇
      villageList: [], // 调整账单项目
      villageAndBuildList: [], // 请求接口后缓存
      adjustTypeOption: [], // 调整类型下拉
      basicsInfo: {}, // 基础信息展示
      contractDetailVisible: false,
      contractDetailId: 0,
      removeAdjustId: 0,
      removeAdjustBillId: 0,
      removeAdjustVisible: false,
      billDetailId: 0,
      billDetailVisible: false,
      isExport: false,
      companyList: [],
      carryDetailVisible: false,
      carryDetailId: 0,
      titles: '',
      paramses: {},
      listHanders: {},
      exportResult: [],
    });

    // 统计下拉
    const statisticsOption = computed(() => [
      {
        value: "receivable_payment_date",
        label: state.activeTab === "1" ? "按应收时间" : "按应支时间",
      },
      {
        value: "start_date",
        label: "按有效期开始时间",
      },
    ]);

    const totalList = computed(() => [
      {
        title: state.activeTab === "1" ? "总应收入" : "总应支出",
        num: state.totalAmount,
      },
      {
        title: state.activeTab === "1" ? "物业费收入" : "物业费支出",
        num: state.propertyAmount,
      },
      {
        title: state.activeTab === "1" ? "其他费收入" : "其他费支出",
        num: state.otherAmount,
      },
      {
        title: state.activeTab === "1" ? "未收金额" : "未支金额",
        num: state.needAmount,
      },
      {
        title: state.activeTab === "1" ? "已收金额" : "已支金额",
        num: state.haveAmount,
      },
    ]);

    const pagination = computed(() => ({
      total: state.total,
      current: state.page,
      pageSize: state.limit,
      showSizeChanger: true,
    }));

    const rowSelection = computed(() =>
      ["1", "2", '6', "7"].includes(state.activeTab)
        ? {
            selectedRowKeys: selectedRowKeys.value,
            onChange: onSelectedRowChange,
          }
        : null
    );

    // 搜索参数
    const searchParams = reactive({
      // 收支
      income: {
        method: "receivable_payment_date", // 统计方式
        month: moment().format(monthFormat), // 统计月份
        owner_name: "", // 租客
        tel: "", // 联系电话
        cost_type: undefined, // 费用类型
        timeout_status: undefined, // 逾期状态
        latefee_status: undefined, // 滞纳金
        build_id: undefined, //楼宇名称
        room_name: "", // 房号
        remit_type: undefined, // 收款方式
        settle_status: undefined, // 结清状态
        org_branch_id: undefined,
      },
      // 调整
      adjust: {
        adjust_type: undefined, // 调整类型
        owner_name: "", // 租客名称
        village_ids: [],
        build_ids: [],
        contract_number: "", // 合同编号
        bill_number: "", // 账单编号
        org_branch_id: undefined,
      },
      // 结转
      carry: {
        businessType: 0, // 业务类型
        cost_type: undefined, // 费用类型
        village_ids: [],
        build_ids: [],
        out_owner_name: '',
        into_owner_name: '',
        out_bill_number: '',
        into_bill_number: '',
        createDate: undefined,
      },
      // 收入单据
      receipts: {
        owner_name: "", // 租客名称
        village_ids: [],
        build_ids: [],
        contract_number: "", // 合同编号
        org_branch_id: undefined,
        cost_type: undefined, // 费用类型
        income_month: undefined, // 收入月份
      }
    });

    /* 收支表格 */
    const isIncomeAndExpenseTable = computed(
      () => state.activeType === "table" && ["1", "2"].includes(state.activeTab)
    );
    /* 收支图表 */
    const isIncomeAndExpenseChart = computed(
      () => state.activeType === "chart" && ["1", "2"].includes(state.activeTab)
    );
    /* 表格 图标 切换按钮显隐 */
    const haveToggle = computed(() => ["1", "2"].includes(state.activeTab));
    /* 调整表格 */
    const isAdjustTable = computed(() => ["5"].includes(state.activeTab));

    /* 结转表格 */
    const isCarryOverTable = computed(() => ["6"].includes(state.activeTab));

    /* 收入单据表格 */
    const isReceiptsTable = computed(() => ["7"].includes(state.activeTab));
    /* 表格列 */
    const activeColumn = computed(() => {
      return state.activeTab == "1"
        ? state.incomeColumns
        : state.activeTab == "2"
        ? state.expenseColumns
          : state.activeTab == "6" ? state.carryOverColumns : state.activeTab == "7" ? state.receiptsColumns : state.adjustColumns;
    });

    // 选择应收账单
    const selectedRowKeys = ref([]);
    const onSelectedRowChange = (keys) => {
      if (keys.length > 100) {
        notification.warning({
          message: "警告",
          description: "您最多可勾选100项",
        });
        return;
      }
      selectedRowKeys.value = keys;
    };

    const { resetFields } = useForm(searchParams, {});

    const getTableData = (init = false) => {
      state.loading = true;
      if (init) {
        state.page = 1;
        state.dataList = [];
        state.total = 0;
        state.basicsInfo = {};
      }
      let params = {
        page: state.page,
        limit: state.limit,
        bill_type: state.activeTab,
      };
      let searchParamsKey = isAdjustTable.value ? "adjust" : isCarryOverTable.value ? "carry" : isReceiptsTable.value ? "receipts" : "income";
      let paramsObj = searchParams[searchParamsKey] || {};
      for (let key in paramsObj) {
        if (paramsObj[key] || paramsObj[key] === 0) {
          if (
            ["bill_source", "cost_type"].includes(key) &&
            paramsObj[key]?.length
          ) {
            params[key] = paramsObj[key][paramsObj[key].length - 1];
          } else if (
            [ 'org_branch_id'].includes(key) &&
            paramsObj[key]?.length
          ) {
            params[key] = paramsObj[key].join(",");
          } else if ( key == 'createDate' && paramsObj[key]?.length ) {
            params.start_date = paramsObj[key][0];
            params.end_date = paramsObj[key][1];
          }  else {
            params[key] = paramsObj[key];
          }
        }
      }
      let url = isAdjustTable.value
        ? "/bill/adjustBillList" : isCarryOverTable.value ? '/billTransfer/transferFinanceList' : isReceiptsTable.value ? '/incomeConfirm/incomeReceiptList'
        : "/bill/reportList";
      if (isAdjustTable.value || isCarryOverTable.value || isReceiptsTable.value) {
        delete params.bill_type;
      }
      request
        .post("/org", url, params)
        .then((res) => {
          state.dataList = res.list;
          state.total = res.total;
          state.basicsInfo = res;
        })
        .finally(() => {
          state.loading = false;
        });
    };

    // 获取总计数据
    const getTotal = (params) => {
      state.totalSpin = true;
      request
        .get("/org", "/bill/report/receiveCollectData", params)
        .then((res) => {
          state.totalAmount = res?.totalAmount || 0;
          state.propertyAmount = res?.propertyAmount || 0;
          state.otherAmount = res?.otherAmount || 0;
          state.needAmount = res?.needAmount || 0;
          state.haveAmount = res?.haveAmount || 0;
        })
        .finally(() => {
          state.totalSpin = false;
        });
    };

    const getChartData = () => {
      let params = {
        month: moment(searchParams.income.month).format(monthFormat),
        method: searchParams.income.method,
        bill_type: state.activeTab,
      };
      getTotal(params);
      getPieChart();
      getBarChart();
    };

    const getDataList = (init = false) => {
      if (["1", "2"].includes(state.activeTab)) {
        if (state.activeType === "table") {
          getTableData(init);
        } else if (state.activeType === "chart") {
          getChartData(init);
        }
      } else {
        getTableData(init);
      }
    };

    const onTabChange = (active) => {
      selectedRowKeys.value = [];
      if (["1", "2"].includes(active)) {
        getDataList(true);
      } else {
        getTableData(true);
      }
    };

    const reset = () => {
      resetFields();
      getDataList(true);
    };

    // 一键批量催缴
    const addPaymentNoticeBatch = (type, id) => {
      let params = [];
      let isCover = false;
      if (type === "one" && id) {
        params = [id];
      } else if (selectedRowKeys.value.length) {
        isCover = true;
        params = selectedRowKeys.value;
      } else {
        params = state.basicsInfo?.overdueBillIds || [];
      }
      if (params.length) {
        request
          .post("/org", "/notice/beforeVerify", {
            billIds: params,
            needMsg: true,
          })
          .then((res) => {
            if (res.data.pass) {
              if (isCover) {
                selectedRowKeys.value = res.data.matchIds;
              }
              state.addNoticeIds = res.data.matchIds;
              state.addNoticeVisible = true;
            } else {
              Modal.confirm({
                title: "提示",
                content: () => res.msg,
                icon: () => createVNode(ExclamationCircleOutlined),
                centered: true,
                okText: () => "继续",
                onOk() {
                  if (isCover) {
                    selectedRowKeys.value = res.data.matchIds;
                  }
                  state.addNoticeIds = res.data.matchIds;
                  state.addNoticeVisible = true;
                },
              });
            }
          })
          .catch((err) => {
            console.log(err);
            if (err.code == 60023) {
              Modal.info({
                title: "提示",
                content: () => err.msg,
                centered: true,
                okText: () => "确定",
              });
            }
          });
      } else {
        message.warning("暂无数据~");
      }
    };

    const handleTableChange = (pager) => {
      state.page = pager.current;
      state.limit = pager.pageSize;
      getDataList();
    };

    // 导出报表
    let timer = null;
    const iframe = document.createElement("iframe");
    const downLoadClick = (type) => {
      let params = {
        bill_type: state.activeTab,
        ids: selectedRowKeys.value,
      };
      let paramsObj = searchParams[type] || {};
      for (let key in paramsObj) {
        if (paramsObj[key] || paramsObj[key] === 0) {
          if (
            ["bill_source", "cost_type"].includes(key) &&
            paramsObj[key]?.length
          ) {
            params[key] = paramsObj[key][paramsObj[key].length - 1];
          } else if (
            [ 'org_branch_id'].includes(key) &&
            paramsObj[key]?.length
          ) {
            params[key] = paramsObj[key].join(",");
          } else if ( key == 'createDate' && paramsObj[key]?.length ) {
            params.start_date = paramsObj[key][0];
            params.end_date = paramsObj[key][1];
          }  else {
            params[key] = paramsObj[key];
          }
        }
      }
      if (type === 'receipts') {
        delete params.bill_type;
        state.titles = "收入单据列表" + moment().format("YYYY-MM-DD-HH:mm:ss");
        params.page = 1;
        params.limit = 10000;
        state.listHanders = state.receiptsColumns.reduce((obj, v) => {
          obj[v.dataIndex] = v.title;
          return obj;
        }, {});
        state.paramses = params;
        state.isExport = true;
      } else {
        if (timer) {
          message.warn("操作过于频繁，请稍后尝试");
          return;
        }
        let url = '/bill/reportExport';
        if (type === 'carry') {
          delete params.bill_type
          url = '/billTransfer/exportBillTransfer'
        }
        if (type === 'adjust') {
          delete params.bill_type
          url = '/newBill/exportAdjustBillList';
        }
        request.post("/org", url, { ...params }).then((res) => {
          iframe.src = res.result.fileUrl;
          iframe.style.display = "none";
          document.body.appendChild(iframe);
          setTimeout(() => {
            document.body.removeChild(iframe);
          }, 1000);
          message.success("导出成功,请等待文件生成");
          timer = setTimeout(() => {
            timer = null;
          }, 20000);
        });
      }

    };

    /** 查看租客 */
    const onOwnerClick = (id) => {
      if (id) {
        state.ownerId = id;
        state.ownerDetailVisible = true;
      }
    };
    /** 查看租客 || 业主 */
    const onOwnerCollectClick = (record) => {
      if (record.owner_id) {
        state.ownerId = record.owner_id;
        state.ownerDetailVisible = true;
      } else if (record.proprietor_id) {
        if (record.is_new == 1) {
          state.ownerId = record.proprietor_id;
          state.ownerDetailVisible = true;
        } else {
          state.proprietorId = record.proprietor_id;
          state.proprietorDetailVisible = true;
        }
      }
    };

    const handleSearch = () => {
      selectedRowKeys.value = [];
      getDataList(true);
    };


    const isBeyond = (e) => {
      const ev = window.event || e;
      const textContent = ev?.target;
      const clientW = textContent?.clientWidth;
      const scrollW = textContent?.scrollWidth;
      return scrollW > clientW; // true为溢出  false为不溢出
    };

    const handleEnter = (e, item) => {
      item.isOpen = isBeyond(e);
    };

    // 切换表格/图表
    const changeTotalType = () => {
      selectedRowKeys.value = [];
      getDataList(true);
    };

    const onVillageChange = (value, option, type) => {
      let vbList = _.cloneDeep(state.villageAndBuildList);
      let bList = [];
      if (value.length > 0) {
        vbList = state.villageAndBuildList.filter((village) =>
          value.includes(village.id)
        );

        // 筛选项目时清除楼宇选中项
        searchParams[type].build_ids = [];
      }
      vbList.forEach((village) => {
        if (village.buildList && village.buildList.length > 0) {
          village?.buildList?.forEach((build) => {
            bList.push({
              label: build.build_name,
              value: build.id,
            });
          });
        }
      });
      state.buildList[type] = bList;
    };

    // 楼宇筛选
    const getBuildList = () => {
      request
        .get("/org", "/build/villageAndBuildList/v2", {
          checked: 1,
        })
        .then((res) => {
          state.villageAndBuildList = res.villageList;
          state.buildOption = [];
          Object.keys(state.buildList).forEach((key) => {
            state.buildList[key] = [];
          });
          state.villageList = [];
          let vList = [];
          let bList = [];
          res.villageList.forEach((village) => {
            vList.push({
              label: village.name,
              value: village.id,
            });
            village?.buildList?.forEach((build) => {
              bList.push({
                label: build.build_name,
                value: build.id,
              });
            });
          });
          state.villageList = _.cloneDeep(vList);
          Object.keys(state.buildList).forEach((key) => {
            state.buildList[key] = _.cloneDeep(bList);
          });
          state.buildOption = _.cloneDeep(bList);
        });
    };

    const getCostTypeSub = (selectedOptions) => {
      const targetOption = selectedOptions[selectedOptions.length - 1];
      targetOption.loading = true;
      request
        .get("/org", "/bill/costList", {
          page: 1,
          limit: 9999,
          category_id: targetOption.value,
          status: 1,
        })
        .then((res) => {
          if (res.list) {
            targetOption.loading = false;
            targetOption.children = res.list.map((item) => ({
              label: item.name,
              value: item.cost_type,
              isLeaf: true,
            }));
            state.costTypeOption = [...state.costTypeOption];
          }
        });
    };

    const getCostTypeList = () => {
      request.get("/org", "/bill/cost/categoryList", {}).then((res) => {
        if (res.list) {
          state.costTypeOption = res.list.map((item) => ({
            label: item.name,
            value: item.id,
            isLeaf: false,
          }));
        }
      });
    };

    // 合同详情
    const onContractClick = (id) => {
      if (id) {
        state.contractDetailId = id;
        state.contractDetailVisible = true;
      }
    };

    // 作废调整金
    const handleAdjustRemove = (record) => {
      state.removeAdjustBillId = record.bill_id;
      state.removeAdjustId = record.id;
      state.removeAdjustVisible = true;
    };

    // 账单详情
    const clickBillNum = (id) => {
      state.billDetailId = id;
      state.billDetailVisible = true;
    };

    const cancelBill = () => {
      state.billDetailVisible = false;
      getTableData();
    };

    const handleAdjustRemoveSuccess = () => {
      state.removeAdjustVisible = false;
      getTableData();
    };

    const handleTableRowClick = (record) => {
      // 结转详情
      state.carryDetailId = record.id;
      if (state.carryDetailId) {
        state.carryDetailVisible = true;
      }
    };

    // 自定义行
    const customRow = (record) => {
      return {
        style: {
          cursor: "pointer",
        },
        onClick: (e) => handleTableRowClick(record),
      };
    };

    const handleCancelCarryDetail = () => {
      state.carryDetailVisible = false;
      state.carryDetailId = 0;
    };

    const handleRefresh = () => {
      getTableData();
    };

    const handleCustomResult = (list) => {
      state.exportResult = list;
    };

    const handleChangeExport = () => {
      state.isExport = false;
      message.success("导出成功,请等待文件生成");
    };

    const init = () => {
      store.dispatch("BillInit").then((data) => {
        state.timeoutOption = data?.timeout_status || [];
        state.lateFeeOption = data?.latefee_status || [];
        state.remitTypeOption = data?.remit_type || [];
        state.settleOption = data?.settle_status || [];
        state.billSourceOption = data?.bill_source || [];
        state.currencyOption = data?.currency || [];
        state.adjustTypeOption = data?.adjust_type || [];
        state.companyList = data?.org_branch_id || [];
        getCostTypeList();
        getBuildList();
        getDataList(true);
      });
    };

    init();

    const getPieChart = (isMount) => {
      if (_.isEmpty(state.pieChart)) {
        state.pieChart = new Chart({
          container: "bill-statement-report-pie",
          autoFit: true,
        });
        state.pieChart.coordinate("theta", {
          radius: 0.75,
          innerRadius: 0.65,
        });
        state.pieChart.scale("percent", {
          formatter: (val) => {
            val == 0 ? (val = null) : (val = val + "%");
            return val;
          },
        });

        state.pieChart.legend(false);

        state.pieChart.tooltip({
          showCrosshairs: false,
          showMarkers: false,
        });

        state.pieChart
          .interval()
          .adjust("stack")
          .position("percent")
          .label("percent", {
            layout: [{ type: "limit-in-plot", cfg: { action: "ellipsis" } }],
            content: (data) => {
              return `${data.name}: ${data.percent}%`;
            },
          })
          .color("name", state.color)
          .style({
            fillOpacity: 1,
          })
          .state({
            active: {
              style: (element) => {
                const shape = element.shape;
                return {
                  lineWidth: 10,
                  stroke: shape.attr("fill"),
                  strokeOpacity: shape.attr("fillOpacity"),
                };
              },
            },
          });

        // 移除图例点击过滤交互
        state.pieChart.removeInteraction("legend-filter");
        state.pieChart.interaction("element-active");
      }

      if (!isMount) {
        state.pieSpin = true;
        let params = {
          month: moment(searchParams.income.month).format(monthFormat),
          method: searchParams.income.method,
          bill_type: state.activeTab,
        };
        request
          .get("/org", "/bill/report/remitAmountRatio", params)
          .then((res) => {
            state.pieData = res?.list || [];
            state.pieChart.annotation().clear(true);
            state.pieChart
              .annotation()
              .text({
                position: ["50%", "50%"],
                content: "总笔数",
                style: {
                  fontSize: 12,
                  fill: "#8c8c8c",
                  textAlign: "center",
                },
                offsetY: -20,
              })
              .text({
                position: ["50%", "50%"],
                content:
                  Number(
                    state.pieData.reduce((total, currentValue) => {
                      return total + currentValue.total;
                    }, 0)
                  ) + "笔",
                style: {
                  fontSize: 30,
                  fill: "#6f6f6f",
                  textAlign: "center",
                },
                offsetY: 10,
              });
            state.pieChart.changeData(state.pieData);
            state.pieChart.render();
            nextTick(() => {
              state.pieChart.forceFit();
            });
          })
          .finally(() => {
            state.pieSpin = false;
          });
      } else {
        state.pieChart.render();
      }
    };

    const getBarChart = (isMount) => {
      if (_.isEmpty(state.barChart)) {
        state.barChart = new Chart({
          container: "bill-statement-report-bar",
          autoFit: true,
        });
        state.barChart.scale({
          percent: {
            max: 100,
            min: 0,
            nice: true,
          },
        });

        state.barChart.tooltip({
          showMarkers: false,
        });

        state.barChart.interaction("active-region");
        state.barChart
          .interval()
          .position("name*total")
          .color("title")
          .size(20);
        state.barChart.legend(false);
      }
      if (!isMount) {
        let params = {
          month: moment(searchParams.income.month).format(monthFormat),
          method: searchParams.income.method,
          bill_type: state.activeTab,
        };
        state.barSpin = true;
        request
          .get("/org", "/bill/report/costTypeTrendList", params)
          .then((res) => {
            let list = res?.list || [];
            list = list.map((v) => {
              v.title = "金额";
              return v;
            });
            state.barData = list;
            state.barChart.changeData(state.barData);
            state.barChart.render();
            nextTick(() => {
              state.barChart.forceFit();
            });
          })
          .finally(() => {
            state.barSpin = false;
          });
      } else {
        state.barChart.render();
      }
    };

    onMounted(() => {
      getBarChart(true);
      getPieChart(true);
    });

    onUnmounted(() => {
      if (!_.isEmpty(state.pieChart)) {
        state.pieChart.destroy();
      }
      if (!_.isEmpty(state.barChart)) {
        state.barChart.destroy();
      }
    });

    return {
      ...toRefs(state),
      searchParams,
      statementTabs,
      monthFormat,
      pagination,
      isIncomeAndExpenseTable,
      isIncomeAndExpenseChart,
      statisticsOption,
      selectedRowKeys,
      totalList,
      simpleImage,
      BLCOMMON,
      haveToggle,
      isAdjustTable,
      isCarryOverTable,
      dateFormatStr,
      activeColumn,
      rowSelection,
      canCancelAdjust,
      isReceiptsTable,
      reset,
      getDataList,
      handleTableChange,
      onTabChange,
      downLoadClick,
      onOwnerClick,
      handleSearch,
      onSelectedRowChange,
      onOwnerCollectClick,
      handleEnter,
      changeTotalType,
      getCostTypeSub,
      onVillageChange,
      onContractClick,
      addPaymentNoticeBatch,
      handleAdjustRemove,
      handleAdjustRemoveSuccess,
      clickBillNum,
      cancelBill,
      customRow,
      handleCancelCarryDetail,
      handleRefresh,
      handleCustomResult,
      handleChangeExport,
    };
  },
});

const statementTabs = [
  {
    key: "1",
    title: "应收报表",
  },
  {
    key: "2",
    title: "应支报表",
  },
  {
    key: "5",
    title: "调整单据",
  },
  {
    key: "6",
    title: "结转报表",
  },
  {
    key: "7",
    title: "收入单据",
  },
  // {
  //   key: 'statistics',
  //   title: '收支计划统计报表',
  // },
];
const INCOME_COLUMNS = [
  {
    title: BLCOMMON.utils.L("租客"),
    dataIndex: "owner_name",
    key: "owner_name_income",
    slotKey: "owner_name",
    width: 120,
    fixed: "left",
  },
  {
    title: "默认联系人",
    dataIndex: "contact_name",
    key: "contact_name_income",
    width: 120,
  },
  {
    title: "联系电话",
    dataIndex: "owner_tel",
    key: "owner_tel_income",
    width: 150,
  },
  {
    title: "楼宇名称",
    dataIndex: "build_name",
    key: "build_name_income",
    width: 100,
  },
  {
    title: "房号",
    dataIndex: "room_number_txt",
    slotKey: "room_number",
    key: "room_number_txt_income",
    width: 100,
  },
  {
    title: "有效期",
    dataIndex: "start_date",
    key: "start_date_income",
    width: 240,
    customRender: ({ text, record, index }) => {
      return record?.start_date + "至" + record?.end_date;
    },
  },
  {
    title: "费用类型",
    dataIndex: "cost_type_txt",
    key: "cost_type_txt_income",
    width: 120,
  },
  {
    title: "应收金额",
    dataIndex: "receivable_payment",
    key: "receivable_payment_income",
    width: 120,
    customRender: ({ text, record, index }) => {
      return "￥" + text || 0;
    },
  },
  {
    title: "应收时间",
    key: "receivable_payment_date_income",
    dataIndex: "receivable_payment_date",
    width: 120,
  },
  {
    title: "逾期状态",
    key: "timeout_status_txt_income",
    dataIndex: "timeout_status_txt",
    width: 100,
  },
  {
    title: "滞纳金",
    key: "need_latefee_income",
    dataIndex: "need_latefee",
    width: 120,
    customRender: ({ text, record, index }) => {
      return text || 0;
    },
  },
  {
    title: "实收款",
    key: "actual_payment_income",
    dataIndex: "actual_payment",
    width: 120,
    customRender: ({ text, record, index }) => {
      return text ? "￥" + text : "--";
    },
  },
  {
    title: "收款方式",
    key: "remit_type_txt_income",
    dataIndex: "remit_type_txt",
    width: 120,
    customRender: ({ text, record, index }) => {
      return text || "--";
    },
  },
  {
    title: "缴费通知单",
    key: "action_income",
    dataIndex: "id",
    slotKey: "action",
  },
];
const EXPENSE_COLUMNS = [
  {
    title: "收款方姓名",
    dataIndex: "owner_name",
    slotKey: "proprietor_name",
    key: "owner_name_expense",
    width: 120,
    fixed: "left",
  },
  {
    title: "默认联系人",
    key: "contact_name_expense",
    dataIndex: "contact_name",
    width: 120,
  },
  {
    title: "联系电话",
    key: "owner_tel_expense",
    dataIndex: "owner_tel",
    width: 150,
  },
  {
    title: "楼宇名称",
    key: "build_name_expense",
    dataIndex: "build_name",
    width: 100,
  },
  {
    title: "有效期",
    key: "start_date_expense",
    dataIndex: "start_date",
    width: 240,
    customRender: ({ text, record, index }) => {
      return record?.start_date + "至" + record?.end_date;
    },
  },
  {
    title: "费用类型",
    key: "cost_type_txt_expense",
    dataIndex: "cost_type_txt",
    width: 120,
  },
  {
    title: "应支金额",
    key: "receivable_payment_expense",
    dataIndex: "receivable_payment",
    width: 120,
    customRender: ({ text, record, index }) => {
      return "￥" + text || 0;
    },
  },
  {
    title: "实付时间",
    key: "entry_date_expense",
    dataIndex: "entry_date",
    width: 120,
    customRender: ({ text, record, index }) => {
      return text || "--";
    },
  },
  {
    title: "币种",
    key: "currency_txt_expense",
    dataIndex: "currency_txt",
    width: 100,
  },
  {
    title: "应付时间",
    key: "receivable_payment_date_expense",
    dataIndex: "receivable_payment_date",
    width: 120,
  },
  {
    title: "逾期状态",
    key: "timeout_status_txt_expense",
    dataIndex: "timeout_status_txt",
    width: 100,
  },
];

const ADJUST_COLUMNS = [
  {
    title: BLCOMMON.utils.L("租客") + "名称",
    dataIndex: "owner_name",
    key: "owner_name_adjust",
    slotKey: "owner_name",
    fixed: "left",
  },
  {
    title: "楼宇名称",
    key: "build_name_adjust",
    dataIndex: "build_name",
  },
  {
    title: "合同编号",
    dataIndex: "contract_number",
    key: "contract_number_adjust",
    slotKey: "contract_number",
    width: 240,
  },
  {
    title: "财务编号",
    dataIndex: "bill_number",
    slotKey: "bill_number",
    key: "bill_number_adjust",
    width: 240,
  },
  {
    title: "账单状态",
    dataIndex: "bill_status_txt",
    key: "bill_status_txt_adjust",
  },
  {
    title: "逾期状态",
    dataIndex: "timeout_status_txt",
    key: "timeout_status_txt_adjust",
  },
];

const ADJUST_INNER_COLUMNS = [
  {
    title: "调整日期",
    key: "adjust_date_adjust",
    dataIndex: "adjust_date",
  },
  {
    title: "调整类型",
    key: "adjust_type_txt_adjust",
    dataIndex: "adjust_type_txt",
  },
  {
    title: "调整方式",
    key: "adjust_mode_txt_adjust",
    dataIndex: "adjust_mode_txt",
  },
  {
    title: "调整金额（元）",
    key: "adjust_price_adjust",
    dataIndex: "adjust_price",
  },
  {
    title: "备注内容",
    key: "remark_adjust",
    dataIndex: "remark",
    width: 240,
  },
  {
    title: "作废调整日期",
    key: "cancel_adjust_date_adjust",
    dataIndex: "cancel_adjust_date",
  },
  {
    title: "调整状态",
    key: "adjust_status_txt_adjust",
    dataIndex: "adjust_status_txt",
    slotKey: "adjust_status",
  },
  {
    title: "操作",
    key: "action_adjust",
    slotKey: "action",
    dataIndex: "id",
  },
];

const CARRY_OVER_COLUMNS =  [
  {
    title: '结转日期',
    dataIndex: "created_at",
    key: "carry_created_at",
    width: 160,
  },
  {
    title: "业务类型",
    dataIndex: "business_type_txt",
    key: "carry_business_type_txt",
    width: 120,
  },
  {
    title: "结转金额",
    dataIndex: "amount",
    key: "carry_amount",
    width: 160,
    customRender: ({ text, record, index }) => {
      return "￥" + record?.amount;
    },
  },
  {
    title: "转出对方名称",
    dataIndex: "out_owner_name",
    key: "carry_out_owner_name",
    width: 160,
    slotKey: "carry_out_owner_id",
  },
  {
    title: "转出项目楼宇",
    dataIndex: "out_village_name",
    key: "carry_out_village_name",
    customRender: ({ text, record, index }) => {
      return record?.out_village_name + "-" + record?.out_build_name;
    },
    width: 180,
  },
  {
    title: "转出楼层房号",
    dataIndex: "out_roomInfo",
    key: "carry_out_roomInfo",
    width: 180,
  },
  {
    title: "转出费用类型",
    dataIndex: "out_cost_type_txt",
    key: "carry_out_cost_type_txt",
    width: 180,
  },
  {
    title: "转出账单编号",
    dataIndex: "out_bill_number",
    key: "carry_out_bill_number",
    width: 200,
    slotKey: "carry_out_bill_number",
  },
  {
    title: "转入对方名称",
    dataIndex: "into_owner_name",
    key: "carry_into_owner_name",
    slotKey: "carry_into_owner_id",
    width: 160,
  },
  {
    title: "转入项目楼宇",
    dataIndex: "into_village_name",
    key: "carry_into_village_name",
    customRender: ({ text, record, index }) => {
      return record?.into_village_name + "-" + record?.into_build_name;
    },
    width: 180,
  },
  {
    title: "转入楼层房号",
    dataIndex: "into_roomInfo",
    key: "carry_into_roomInfo",
    width: 180,
  },
  {
    title: "转入费用类型",
    dataIndex: "into_cost_type_txt",
    key: "carry_into_cost_type_txt",
    width: 180,
  },
  {
    title: "转入账单编号",
    dataIndex: "into_bill_number",
    key: "carry_into_bill_number",
    slotKey: "carry_into_bill_number",
    width: 200,
  },
];

const RECEIPTS_COLUMNS = [
  {
    title: BLCOMMON.utils.L("租客"),
    dataIndex: "owner_name",
    key: "owner_name_receipts",
    slotKey: "owner_name",
    width: 120,
    fixed: "left",
  },
  {
    title: "项目名称",
    dataIndex: "village_name",
    key: "village_name_receipts",
    width: 120,
  },
  {
    title: "楼宇名称",
    key: "build_name_receipts",
    dataIndex: "build_name",
    width: 120,
  },
  {
    title: "楼层-房号",
    key: "room_number_txt_receipts",
    dataIndex: "room_number_txt",
    width: 120,
  },
  {
    title: "费用类型",
    key: "cost_type_txt_receipts",
    dataIndex: "cost_type_txt",
    width: 120,
  },
  {
    title: "合同编号",
    dataIndex: "contract_number",
    key: "contract_number_receipts",
    slotKey: "contract_number",
    width: 240,
  },
  {
    title: "收入月份",
    dataIndex: "y_m",
    key: "y_m_receipts",
    width: 120,
  },
  {
    title: "应收（不含税）金额",
    dataIndex: "receivable_without_tax",
    key: "receivable_without_tax_receipts",
    width: 200,
  },
  {
    title: "实收（不含税）金额",
    dataIndex: "actual_without_tax",
    key: "actual_without_tax_receipts",
    width: 200,
  },
  {
    title: "确认收入金额",
    dataIndex: "confirm_income_amount",
    key: "confirm_income_amount_receipts",
    width: 200,
  },
  {
    title: "所属公司",
    dataIndex: "org_branch_name",
    key: "org_branch_name_receipts",
    width: 180,
  },
  {
    title: "单据创建日期",
    dataIndex: "create_time",
    key: "create_time_receipts",
    width: 180,
  },
]
</script>

<style lang="less" scoped>
.bill-statement {
  padding: 10px;
  .tab-row {
    background: #fff;
    padding: 0 10px;
  }
  .search-row {
    margin: 10px 0 0 0 !important;
    background: #fff;
    padding: 16px 0 0 0;
  }
  :deep(.ant-tabs-bar) {
    margin: 0;
  }
  :deep(.ant-radio-button-wrapper) {
    padding: 0 18px;
  }

  .statement-content {
    margin-top: 1px;
    background: #fff;
    padding: 0 10px;
    .theretext{
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 3; //行数需设置
      line-clamp: 3;
      -webkit-box-orient: vertical;
    }
  }

  .title-card-text {
    height: 40px;
    width: 100%;
    font-size: 16px;
    font-weight: bold;
    color: rgba(0, 0, 0, 0.8);
    position: relative;
    padding: 20px 12px;
    display: flex;
    align-items: center;
    &::before {
      position: absolute;
      content: "";
      left: 0;
      top: 12px;
      bottom: 12px;
      width: 6px;
      border-radius: 4px;
      background-color: @primary-color;
    }
  }

  :deep(.ant-card-head-title) {
    padding: 4px 0;
  }

  .total-box {
    width: 100%;
    padding: 0 20px;
    display: flex;
  }
  .total-item {
    flex: 1;
    display: flex;
    align-items: center;
    width: 0;
    margin-right: 10px;
  }
  .dec-left {
    justify-content: left;
  }
  .dec-right {
    justify-content: right;
  }
  .item-dec {
    display: flex;
    flex-direction: column;
    align-items: center;
    max-width: 100%;
    height: 60px;
    justify-content: space-between;
  }
  .total-num {
    max-width: 100%;
    font-size: 22px;
    font-weight: 600;
    word-break: break-all;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
  }
  .total-dec {
    max-width: 100%;
    color: #666;
    font-weight: 600;
    font-size: 14px;
    word-break: break-all;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
  }
  .border-right {
    border-right: 1px solid #ddd;
  }
  :deep(.ant-card-extra) {
    padding: 0;
  }
}

:deep(.ant-spin-nested-loading) {
  height: 100%;
}
:deep(.ant-spin-container) {
  height: 100%;
}

.overview-box {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  .custom-legend {
    height: 50px;
    width: 100%;
    display: flex;
    justify-content: space-between;
    &-item {
      display: flex;
      flex-direction: column;
      flex: 1;
      align-items: center;
      justify-content: space-around;
      .item-count {
        font-size: 18px;
        font-weight: 600;
        color: #666666;
      }
      .item-title {
        display: flex;
        font-size: 12px;
        align-items: center;
      }
      &:not(:last-child) {
        border-right: 1px solid #e9e9e9;
      }
    }
  }
  .chart {
    flex: 1;
  }
}
.circle {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  margin-right: 2px;
}
.break-a {
  word-break: break-all;
  display: block;
}
.statistics {
  margin-top: 10px;
  .quantity {
    width: 100%;
    background-color: #fff;
    height: 120px;
    align-items: center;
    padding: 10px;
    .text-center {
      text-align: center;
      position: relative;
      flex: 1;
      width: 0;
      .text {
        color: #8d8d8d;
      }
      .number-width {
        color: @primary-color;
        font-weight: 700;
        font-size: 26px;
        width: 100%;
        // 文字不折行
        overflow: hidden;
        word-break: break-all;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
    }
  }
  .text-center:not(:last-child):after {
    content: "";
    position: absolute;
    right: 0;
    top: 25%;
    height: 50%;
    border-left: 1px solid #e6e5e5;
  }
}
</style>
